package com.yjd.msg.comm.aspect;

import com.alibaba.fastjson.JSON;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.msg.MnsMsgInfo;
import com.yjd.comm.util.FrameUtil;
import com.yjd.msg.comm.annotation.MnsDispose;
import com.yjd.msg.comm.model.MsgDisposeModel;
import com.yjd.msg.comm.service.IMsgDisposeService;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import javax.annotation.Resource;

/**
 * 处理消息拦截
 * Created by yjd-wap on 2018/1/24.
 */
@Aspect
@Order(value = 100002)
public class MnsMsgDisposeAspect {
    private static Logger logger = Logger.getLogger(MnsMsgDisposeAspect.class);

    @Resource
    private IMsgDisposeService msgDisposeService;

    @Around(value = "execution(* com.yjd..*ServiceImpl.*(..)) && @annotation(dispose)")
    public Object invoke(ProceedingJoinPoint invocation, MnsDispose dispose) throws Throwable {
        Object result = "";
        MnsMsgInfo mnsMsgInfo = (MnsMsgInfo)invocation.getArgs()[0];
        try {
            MsgDisposeModel msgDisposeModel = msgDisposeService.getModelOne(FrameUtil.newHashMap("customer_name",mnsMsgInfo.getCustomer_name(),"ref_id",
                    mnsMsgInfo.getBus_id()), DbWREnums.READ);
            if(msgDisposeModel==null){
                //如果当前消息未被消费，执行业务方法消费当前消息
                result = invocation.proceed();
                //消费完成则记录到本地消息消费表中
                msgDisposeService.insert(new MsgDisposeModel(mnsMsgInfo.getBus_id(),mnsMsgInfo.getCustomer_name(),FrameUtil.getTime()));
            }
            return result;
        } catch (Exception e) {
            logger.error("####消费当前消息异常，消息："+JSON.toJSONString(mnsMsgInfo)+"异常信息:" + e);
            throw e;
        }
    }
}
